package com.geek.novel.service

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.*
import android.widget.RemoteViews
import android.widget.Toast
import com.geek.novel.R
import com.geek.novel.activity.main.MainActivity
import com.geek.novel.utils.DownloadUtil
import com.geek.novel.utils.FileUtil
import com.geek.novel.utils.LogCatUtil
import java.io.File

/**

 *
 *  * 功能描述: 新版本下载服务
 *  * 版本描述:
 *  * date: 2015-11-20
 *  * 修改描述:
 *
 */
class UpdateService : Service() {

    private var apkPath: String? = null
    private var apkName: String? = null
    private var apkInfo = ""
    private var apkSize = ""
//    private var canceled = false
    private var manager: NotificationManager? = null
    private var notification: Notification? = null

    private val notificationId = 0

    @SuppressLint("HandlerLeak")
    private var handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                DownloadUtil.DOWNLOAD_PROGRESS -> {// 更新进度
                    val progress = msg.arg1
                    val completed = progress >= 100
                    myBinder.update(completed, false, progress)
                    if (!completed) {
                        val contentView = notification!!.contentView
                        contentView.setTextViewText(R.id.tv_notify_update_progress, "已下载  " + progress + "%    总共  " + apkSize + "M")
                        contentView.setProgressBar(R.id.notify_update_progressbar, 100, progress, false)
                    }
                    manager!!.notify(notificationId, notification)
                }
                DownloadUtil.DOWNLOAD_SUCCESS -> {// 下载完成，安装apk
                    myBinder.update(completed = true, cancel = false, progress = 100)
                    manager!!.cancel(notificationId)
                    installApk()
                    stopSelf()
                }
                DownloadUtil.CANCEL_DOWNLOAD,
                DownloadUtil.DOWNLOAD_ERROR -> {// 取消更新
                    val err = if(msg.obj == null)null else msg.obj as Throwable
                    myBinder.update(completed = true, cancel = true, progress = 100, err)
                    manager!!.cancel(notificationId)
                    stopSelf()
                }
            }
        }
    }

    private val downloadUtil = DownloadUtil(handler)

    private val myBinder = MyBinder()
    override fun onBind(intent: Intent): IBinder {
        return myBinder
    }

    override fun onDestroy() {
        LogCatUtil.d("???", "销毁service")
        if(manager != null){
            manager!!.cancel(notificationId)
        }
        //下载到一半，删除安装包
        downloadUtil.onDestroy()

        handler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        if (intent != null) {
            if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                apkPath = intent.getStringExtra("path")
                apkName = intent.getStringExtra("name")
                apkInfo = intent.getStringExtra("info")
                apkSize = intent.getStringExtra("size")

                registerBroader()
                setUpNotification()

                downloadUtil.startDownload(intent)

            } else {
                Toast.makeText(this@UpdateService, "SD卡不存在", Toast.LENGTH_SHORT).show()
                stopSelf()
            }
        } else {
            stopSelf()
        }
        //		return START_REDELIVER_INTENT;
        return super.onStartCommand(intent, flags, startId)
    }

    /**
     * 创建通知
     */
    @SuppressLint("NewApi")
    private fun setUpNotification() {
        manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        val icon = R.mipmap.ic_launcher
        val tickerText = "开始下载"
        val `when` = System.currentTimeMillis()
        notification = Notification.Builder(applicationContext)
                .setContentText(tickerText)
                .setTicker("玉米小说正在更新")
                .setSmallIcon(icon)
                .setWhen(`when`)
                .build()
        notification!!.flags = Notification.FLAG_NO_CLEAR

        val contentView = RemoteViews(packageName, R.layout.notify_update_layout)
        contentView.setTextViewText(R.id.notify_update_name, resources.getString(R.string.app_name))
        contentView.setTextViewText(R.id.tv_info, "最新版本: $apkInfo")

        val canceledIntent = Intent("canceled")
        canceledIntent.putExtra("canceled", "canceled")
        val canceledPendingIntent = PendingIntent.getBroadcast(this@UpdateService, 1, canceledIntent, PendingIntent.FLAG_UPDATE_CURRENT)
        contentView.setOnClickPendingIntent(R.id.notify_update_cancel, canceledPendingIntent)

        notification!!.contentView = contentView

        val intent = Intent(this@UpdateService, MainActivity::class.java)
        val contentIntent = PendingIntent.getActivity(
                this@UpdateService, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT)
        notification!!.contentIntent = contentIntent

        manager!!.notify(notificationId, notification)// 发送通知
    }

    /**
     * 取消接收者
     * @author renzhiwen 创建时间 2014-8-16 下午4:05:24
     */
    internal inner class CanceledReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            if ("canceled" == intent.getStringExtra("canceled")) {
                val apkFile = File(apkPath, apkName!!)
                if(apkFile.exists()){
                    apkFile.delete()
                }
                downloadUtil.cancel()
                manager!!.cancel(notificationId)
            }
        }

    }

    /**
     * 注册广播
     */
    private fun registerBroader() {
        val filter = IntentFilter()
        filter.addAction("canceled")
        registerReceiver(CanceledReceiver(), filter)
    }

    /**
     * 安装apk
     */
    private fun installApk() {
        val apkFile = File(apkPath, apkName!!)
        if (!apkFile.exists()) {
            return
        }
        FileUtil.installApk(this@UpdateService, apkFile)
    }

    interface UpdateProgress {
        fun update(completed: Boolean, cancel: Boolean, progress: Int, error: Throwable?=null)
    }

    inner class MyBinder : Binder() {
        var updateProgress: UpdateProgress? = null
        fun setDate(progress: UpdateProgress) {
            updateProgress = progress
        }
        fun update(completed: Boolean, cancel: Boolean, progress: Int, error: Throwable?=null){
            if(updateProgress != null){
                updateProgress!!.update(completed, cancel, progress, error)
            }
        }
    }

}
